package com.chookss.home.knowledge;


import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.LookEntity;
import com.chookss.home.knowledge.adaper.LookListAdapter;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.MyEvent;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.liulishuo.okdownload.DownloadTask;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

@SuppressLint("ValidFragment")
public class LookFragment extends Fragment {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.rvLook)
    RecyclerView rvLook;
    @BindView(R.id.llLookMore)
    LinearLayout llLookMore;
    @BindView(R.id.llLookData)
    LinearLayout llLookData;
    @BindView(R.id.ivLookNoData)
    ImageView ivLookNoData;


    private LookListAdapter lookListAdapter;
    private List<LookEntity> looksList = new ArrayList<>();
    private String LOOKTAG = "Home_LookLists_DownloadFile";//下载文件打的标签

    public LookFragment() {
    }
    public LookFragment(Context mContext) {
        this.mContext =mContext;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_look, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        //注册接受
        if(!EventBus.getDefault().isRegistered(this)){//加上判断
            EventBus.getDefault().register(this);
        }
        return view;
    }

    @Override
    public void onViewStateRestored(@androidx.annotation.Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    private void init() {
        rvLook.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        lookListAdapter = new LookListAdapter(R.layout.item_look, getActivity(), looksList, 0, LOOKTAG);
        rvLook.setAdapter(lookListAdapter);
        rvLook.getItemAnimator().setAddDuration(0);
        rvLook.getItemAnimator().setChangeDuration(0);
        rvLook.getItemAnimator().setMoveDuration(0);
        rvLook.getItemAnimator().setRemoveDuration(0);
        ((DefaultItemAnimator) rvLook.getItemAnimator()).setSupportsChangeAnimations(false);
        registerBoradcastReceiver();
//        getData();
    }

    public void setRefresh() {
        getData();
    }

    public void getData() {
        //获取浏览列表
        Map<String, String> allmap = new HashMap<>();
        allmap.put("pageNum", "1");
        allmap.put("pageSize", "3");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<LookEntity>>>() {
        }.getType(), null, Urls.getLatelyResourceList, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<List<LookEntity>>() {
            @Override
            public void onSuccess(List<LookEntity> data) {
                if (looksList.size() == 0) {
                    looksList.clear();
                    if (data == null || data.size() == 0) {

                    } else {
                        looksList.addAll(data);
                        lookListAdapter.notifyDataSetChanged();
                    }
                } else {
                    if (looksList.size() != data.size()) {
                        looksList.clear();
                        looksList.addAll(data);
                        lookListAdapter.notifyDataSetChanged();
                    } else {
                        if (data.size() == 1) {
                            if (!looksList.get(0).getResourceId().equals(data.get(0).getResourceId())) {
                                looksList.clear();
                                looksList.addAll(data);
                                lookListAdapter.notifyDataSetChanged();
                            }
                        } else if (data.size() == 2) {
                            if (!looksList.get(0).getResourceId().equals(data.get(0).getResourceId()) || !looksList.get(1).getResourceId().equals(data.get(1).getResourceId())) {
                                looksList.clear();
                                looksList.addAll(data);
                                lookListAdapter.notifyDataSetChanged();
                            }
                        } else {
                            if (!looksList.get(0).getResourceId().equals(data.get(0).getResourceId()) || !looksList.get(1).getResourceId().equals(data.get(1).getResourceId()) || !looksList.get(2).getResourceId().equals(data.get(2).getResourceId())) {
                                looksList.clear();
                                looksList.addAll(data);
                                lookListAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                }
                if (looksList.size() == 0) {
                    if (llLookData != null) {
                        llLookData.setVisibility(View.GONE);
                        llLookMore.setVisibility(View.GONE);
                        ivLookNoData.setVisibility(View.VISIBLE);
                    }
                    EventBus.getDefault().post(new MyEvent("LookFragment_No_Data"));
                } else {
                    EventBus.getDefault().post(new MyEvent("LookFragment_Have_Data"));
                    if (llLookData != null) {
                        llLookData.setVisibility(View.VISIBLE);
                        ivLookNoData.setVisibility(View.GONE);
                        if (data.size() >= 3) {
                            llLookMore.setVisibility(View.VISIBLE);
                        } else {
                            llLookMore.setVisibility(View.GONE);
                        }
                    }
                }

            }

            @Override
            public void onError(String errorMsg) {
//                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            HashMap<String, String> map = messageEvent.getHashMap();
            if(map.containsKey("DocumentPreview_error")){
                for (int i = 0; i < looksList.size(); i++) {
                    if (looksList.get(i).getResourceId().equals(map.get("DocumentPreview_error"))) {
                        looksList.get(i).setError(true);

                    }
                }
            }
        }
    }
    @OnClick(R.id.llLookMore)
    public void onClick() {
        Intent intent = new Intent(mContext, LookListActivity.class);
        mContext.startActivity(intent);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                String tag = intent.getAction();

                for (int i = 0; i < looksList.size(); i++) {
                    if (looksList.get(i).getResourceId().equals(recevierDataCode)) {
                        if(!looksList.get(i).isOpen()){
                            if(encryptStatus){
                                looksList.get(i).setOpen(true);
                            }
                            //还未打开
                            dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName, tag);
                        }

                    }
                }

            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName, String newTag) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                KLog.i("---------dealData");
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                startActivity(newIntent);
            }
        } else {
            if (percent > 0 && percent < 100) {

                if (lookListAdapter != null) {
                    looksList.get(position).setProgress(percent);
                    lookListAdapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (lookListAdapter != null) {
                    looksList.get(position).setProgress(100);
                    lookListAdapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(mContext, fileUrl, fileName, recevierDataCode, newTag);
                        }
                    }.start();
                }
            }else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(LOOKTAG);// 获取数据
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))//加上判断
            EventBus.getDefault().unregister(this);

        if (unbinder != null) {
            unbinder.unbind();
        }
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
        }

    }
}
